﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.Exceptions;
using Autodesk.Revit.UI;
using YJKRevitBase.WinForm;
using YJKInspectModel.ModelValidation.FireCompartment;

namespace YJKInspectModel.ModelValidation.Commands
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class CmdFireDefAreaCheck : IExternalCommand
	{
		[DllImport("user32.dll", EntryPoint = "SendMessageA")]
		public static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);

		public Result Execute(ExternalCommandData cmdData, ref string msg, ElementSet elems)
		{
			this.m_uidoc = cmdData.Application.ActiveUIDocument;
			if (CmdFireDefAreaCheck._hWndRevit == null)
			{
				CmdFireDefAreaCheck._hWndRevit = new WindowHandle(Process.GetCurrentProcess().MainWindowHandle);
			}
			Transaction transaction = null;
			Result result;
			try
			{
				if (cmdData == null)
				{
					throw new System.ArgumentNullException("commandData");
				}
				transaction = new Transaction(cmdData.Application.ActiveUIDocument.Document);
				transaction.Start("FireDefAreaCheck");
				transaction.Commit();
				DlgSelectFireDefAreaView dlgSelectFireDefAreaView = new DlgSelectFireDefAreaView(cmdData);
				if (dlgSelectFireDefAreaView.IsDlgValid && dlgSelectFireDefAreaView.ShowDialog() == DialogResult.OK)
				{
					List<ViewPlan> lstView = dlgSelectFireDefAreaView.SelectedViews();
					DlgFireDefAreaResult dlgFireDefAreaResult = new DlgFireDefAreaResult(cmdData, lstView);
					dlgFireDefAreaResult.Show(dlgSelectFireDefAreaView._hWndSelectFloorForm);
					for (;;)
					{
						dlgFireDefAreaResult.ResetContinueBreak();
						try
						{
							this.m_uidoc.Selection.PickObject((Autodesk.Revit.UI.Selection.ObjectType)1);
							continue;
						}
						catch (Exception ex)
						{
							if (!(ex is Autodesk.Revit.Exceptions.OperationCanceledException))
							{
								throw ex;
							}
							if (!dlgFireDefAreaResult.IfBreak)
							{
								continue;
							}
							if (dlgFireDefAreaResult.IfManualEsc)
							{
								dlgFireDefAreaResult.Close();
							}
						}
						break;
					}
				}
				result = Autodesk.Revit.UI.Result.Succeeded;
			}
			catch (Exception ex2)
			{
				msg = ex2.Message;
				if (transaction != null && transaction.HasStarted() && !transaction.HasEnded())
				{
					transaction.RollBack();
				}
				result = Autodesk.Revit.UI.Result.Failed;
			}
			return result;
		}

		public static WindowHandle _hWndRevit;

		private UIDocument m_uidoc;
	}
}
